#include "verifycodewidget.h"


VerifyCodeWidget::VerifyCodeWidget(QWidget *parent)
    : QWidget{parent}, m_randomGenerator(model::getTime())
{
    m_verifyCode = generateVerifyCode();
}

bool VerifyCodeWidget::checkVerifyCode(const QString& verifyCode)
{
    return m_verifyCode.compare(verifyCode, Qt::CaseInsensitive) == 0;
}

void VerifyCodeWidget::refreshVerifyCode()
{
    m_verifyCode = generateVerifyCode();
    update();
}

QString VerifyCodeWidget::generateVerifyCode()
{
    QString code;

    for(int i = 0; i < 4; ++i){
        char c = 'A';
        c += m_randomGenerator.generate() % 26;
        code += c;
    }
    return code;
}

void VerifyCodeWidget::paintEvent(QPaintEvent* event)
{
    (void) event;
    const int width = 180;
    const int height = 80;

    QPainter painter(this);
    QPen pen;
    QFont font("楷体",25,QFont::Bold,true);
    painter.setFont(font);

    // 画点: 添加随机噪点
    for(int i = 0; i < 300; i++)
    {
        pen = QPen(QColor(m_randomGenerator.generate() % 256, m_randomGenerator.generate() % 256, m_randomGenerator.generate() % 256));
        painter.setPen(pen);
        painter.drawPoint(m_randomGenerator.generate() % width, m_randomGenerator.generate() % height);
    }

    // 画线: 添加随机干扰线
    for(int i = 0; i < 5; i++)
    {
        pen = QPen(QColor(m_randomGenerator.generate() % 256, m_randomGenerator.generate() % 256, m_randomGenerator.generate() % 256),
                   qreal(3), Qt::SolidLine);
        painter.setPen(pen);
        painter.drawLine(m_randomGenerator.generate() % width, m_randomGenerator.generate() % height,
                         m_randomGenerator.generate() % width, m_randomGenerator.generate() % height);
    }

    // 画验证码
    // 绘制验证码
    for(int i = 0; i < m_verifyCode.size(); i++)
    {
        pen = QPen(QColor(m_randomGenerator.generate() % 255, m_randomGenerator.generate() % 255, m_randomGenerator.generate() % 255));
        painter.setPen(pen);
        painter.drawText(5+20*i, m_randomGenerator.generate() % 10, 30, 30, Qt::AlignCenter, QString(m_verifyCode[i]));
    }
}

void VerifyCodeWidget::mousePressEvent(QMouseEvent* event)
{
    refreshVerifyCode();
}
